package cool.webstudy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cool.webstudy.admin.constant.enums.DelFlagEnum;
import cool.webstudy.admin.constant.enums.EnabledStatusFlagEnum;
import cool.webstudy.admin.constant.enums.rescode.TeamResCodeEnum;
import cool.webstudy.admin.exception.BusinessException;
import cool.webstudy.admin.mapper.team.TeamMapper;
import cool.webstudy.admin.model.dto.team.CreateTeamDTO;
import cool.webstudy.admin.model.dto.team.PaginationQueryTeamInfoListDTO;
import cool.webstudy.admin.model.dto.team.TeamDetailInfoDTO;
import cool.webstudy.admin.model.dto.team.UpdateTeamDTO;
import cool.webstudy.admin.model.dto.user.UserDetailInfoDTO;
import cool.webstudy.admin.model.po.team.TeamPO;
import cool.webstudy.admin.model.vo.team.PaginationQueryTeamInfoListVO;
import cool.webstudy.admin.model.vo.team.QueryTeamDetailInfoVO;
import cool.webstudy.admin.model.vo.team.QueryTeamRoughInfoVO;
import cool.webstudy.admin.service.TeamService;
import cool.webstudy.admin.utils.UserDetailUtil;
import cool.webstudy.common.utils.UUIDUtil;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 队伍管理接口实现类
 */
@Service
public  class TeamServiceImpl implements TeamService {

    @Autowired
    private TeamMapper teamMapper;

    /**
     *
     * @param unCode 队伍业务主键
     * @return TeamPO 队伍信息实体
     * @description: 判断队伍是否存在，如果存在，则返回该队伍的信息实体
     */
    @Override
    public TeamPO isExist(String unCode) {
        LambdaQueryWrapper<TeamPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamPO::getUnCode, unCode)
                .eq(TeamPO::getName,EnabledStatusFlagEnum.ENABLED.getFlag());
        TeamPO team = teamMapper.selectOne(queryWrapper);
        if (Objects.nonNull(team)){
            return team;
        }
        return null;
    }


    /**
     * @param unCode 业务主键
     * @return QueryTeamDetailInfoVO 查询队伍详细信息接口响应参数模型
     * @description: 查询队伍详细信息
     */
    @Override
    public QueryTeamDetailInfoVO queryTeamDetailInfo(String unCode) {
        LambdaQueryWrapper<TeamPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamPO::getUnCode, unCode)
                .select(TeamPO::getUnCode, TeamPO::getName);
        TeamPO team = teamMapper.selectOne(queryWrapper);

        if (Objects.isNull(team)){
            throw new BusinessException(TeamResCodeEnum.RC_TEAM_NOT_EXIST);
        }

        QueryTeamDetailInfoVO queryTeamDetailInfoVO = new QueryTeamDetailInfoVO();
        queryTeamDetailInfoVO.setUnCode(team.getUnCode());
        queryTeamDetailInfoVO.setName(team.getName());

        return queryTeamDetailInfoVO;
    }

    @Override
    public TeamDetailInfoDTO queryTeamDetailInfoDTO(String unCode) {
        TeamDetailInfoDTO teamDetailInfoDTO = new TeamDetailInfoDTO();
        if (StringUtils.isBlank(unCode)){
            return teamDetailInfoDTO;
        }
        TeamPO team;
        try {
            team = teamMapper.selectOne(new LambdaQueryWrapper<TeamPO>().eq(TeamPO::getUnCode, unCode));
        } catch (Exception e) {
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_QUERY);
        }
        if (Objects.nonNull(team)){

            teamDetailInfoDTO.setUnCode(team.getUnCode());
            teamDetailInfoDTO.setName(team.getName());
            return teamDetailInfoDTO;
        }
        return teamDetailInfoDTO;
    }

    /**
     * @param dto 创建队伍接口请求参数模型
     * @return Boolean 是否成功标识
     * @description: 创建队伍
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTeam(CreateTeamDTO dto){
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        TeamPO team = new TeamPO();
        team.setName(dto.getName());
        team.setUnCode(UUIDUtil.getUUID());
        team.setCreateBy(userDetailInfo.getAccount());
        team.setCreateTime(new Date());
        team.setUpdateBy(userDetailInfo.getAccount());
        team.setUpdateTime(new Date());
        team.setDelFlag(DelFlagEnum.NOT_DEL_FLAG.getFlag());

        try {
            teamMapper.insert(team);
        }catch (Exception e){
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_CREATE);
        }

        return true;
    }

    /**
     * @param dto 更新队伍信息接口请求参数模型
     * @return Boolean 是否成功标识
     * @description: 更新队伍信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTeam(UpdateTeamDTO dto){
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        LambdaUpdateWrapper<TeamPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeamPO::getUnCode,dto.getUnCode())
                .set(StringUtils.isNotBlank(dto.getName()),TeamPO::getName, dto.getName())
                .set(TeamPO::getUpdateBy, userDetailInfo.getAccount())
                .set(TeamPO::getUpdateTime , new Date());

        try {
            teamMapper.update(null,updateWrapper);
        }catch (Exception e){
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_UPDATE);
        }

        return true;
    }

    /**
     * @param unCodeList 业务主键列表
     * @return Boolean 是否成功标识
     * @description: 批量删除队伍
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteTeam(List<String> unCodeList){
        UserDetailInfoDTO userDetailInfo = UserDetailUtil.getUserDetailInfo();
        LambdaUpdateWrapper<TeamPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TeamPO::getUnCode, unCodeList)
                .set(TeamPO::getUpdateBy, userDetailInfo.getAccount())
                .set(TeamPO::getUpdateTime,new Date())
                .set(TeamPO::getDelFlag, DelFlagEnum.DEL_FLAG.getFlag());

        try {
            teamMapper.update(null,updateWrapper);
        }catch (Exception e){
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_DELETE);
        }

        return true;
    }


    /**
     * @param dto 分页获取信息列表接口请求参数基础模型
     * @return Page<PaginationQueryTeamInfoListVO> 分页获取队伍信息列表接口响应模型
     * @description: 分页获取队伍信息列表
     */
    @Override
    public Page<PaginationQueryTeamInfoListVO> paginationQueryTeamInfoList(PaginationQueryTeamInfoListDTO dto) {
        Page<PaginationQueryTeamInfoListVO> paginationQueryTeamInfoListVOPage = new Page<>();
        Page<TeamPO> page = new Page<>(dto.getCurrent(),dto.getPageSize());
        LambdaQueryWrapper<TeamPO> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(dto.getContext()),TeamPO::getName,dto.getContext());

        Page<TeamPO> teamPOPage = teamMapper.selectPage(page,queryWrapper);
        if (Objects.isNull(teamPOPage)){
            return paginationQueryTeamInfoListVOPage;
        }
        List<PaginationQueryTeamInfoListVO> paginationQueryTeamInfoListVOList = new ArrayList<>();
        teamPOPage.getRecords().forEach(teamPO -> {
            PaginationQueryTeamInfoListVO paginationQueryTeamInfoListVO = new PaginationQueryTeamInfoListVO();
            paginationQueryTeamInfoListVO.setUnCode(teamPO.getUnCode());
            paginationQueryTeamInfoListVO.setName(teamPO.getName());

            paginationQueryTeamInfoListVO.setCreateBy(teamPO.getCreateBy());
            paginationQueryTeamInfoListVO.setCreateTime(teamPO.getCreateTime());
            paginationQueryTeamInfoListVO.setUpdateBy(teamPO.getUpdateBy());
            paginationQueryTeamInfoListVO.setUpdateTime(teamPO.getUpdateTime());
            paginationQueryTeamInfoListVOList.add(paginationQueryTeamInfoListVO);
        });
        paginationQueryTeamInfoListVOPage.setRecords(paginationQueryTeamInfoListVOList);
        paginationQueryTeamInfoListVOPage.setCurrent(teamPOPage.getCurrent());
        paginationQueryTeamInfoListVOPage.setPages(teamPOPage.getPages());
        paginationQueryTeamInfoListVOPage.setSize(teamPOPage.getSize());
        paginationQueryTeamInfoListVOPage.setTotal(teamPOPage.getTotal());
        return paginationQueryTeamInfoListVOPage;
    }

    @Override
    public List<QueryTeamRoughInfoVO> queryTeamRoughInfoList() {
        LambdaQueryWrapper<TeamPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(TeamPO::getUnCode,TeamPO::getName);
        try {
            List<TeamPO> teamPOList = teamMapper.selectList(queryWrapper);
            if (Objects.isNull(teamPOList)) {
                return List.of();
            }
            List<QueryTeamRoughInfoVO> queryTeamRoughInfoVOList = new ArrayList<>();
            teamPOList.forEach(teamPO -> {
                QueryTeamRoughInfoVO queryTeamRoughInfoVO = new QueryTeamRoughInfoVO();
                queryTeamRoughInfoVO.setUnCode(teamPO.getUnCode());
                queryTeamRoughInfoVO.setName(teamPO.getName());
                queryTeamRoughInfoVOList.add(queryTeamRoughInfoVO);
            });
            return queryTeamRoughInfoVOList;
        } catch (Exception e) {
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, String> queryTeamRoughInfoMap() {
        LambdaQueryWrapper<TeamPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(TeamPO::getUnCode,TeamPO::getName);
        try {
            List<TeamPO> teamPOList = teamMapper.selectList(queryWrapper);
            if (Objects.isNull(teamPOList)) {
                return Map.of();
            }
            Map<String, String> teamRoughInfoMap = new HashMap<>();
            for (TeamPO teamPO : teamPOList) {
                teamRoughInfoMap.put(teamPO.getUnCode(),teamPO.getName());
            }
            return teamRoughInfoMap;
        } catch (Exception e) {
            throw new BusinessException(TeamResCodeEnum.RC_ERROR_QUERY);
        }
    }
}
